package com.lanou.managerLogin.category.dao;

import com.lanou.managerLogin.category.domain.Category;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class CategoryDaoImpl implements CategoryDao {

    private ComboPooledDataSource dataSource = new ComboPooledDataSource();

    @Override
    public List<Category> selectCname() {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            List<Category> query = qr.query(conn, "select * from category", new BeanListHandler<Category>(Category.class));
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public void updateCname(String cid, String cname) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "update category set cname = ? where cid = ?";
            qr.update(conn, sql, cname, cid);
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteCname(String cid) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "delete from category where cid = ?";
            qr.update(conn, sql, cid);
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertCname(String cname) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            String uuId = UUID.randomUUID().toString();
            String ci = uuId.substring(18);
            String sql = "insert into category(cid,cname) values(?,?)";
            qr.update(conn, sql, ci, cname);
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Category cateCname(String cid) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            Category query = qr.query(conn, "select * from category where cid = ?", new BeanHandler<Category>(Category.class), cid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new Category();
    }

}
